package com.tjsinfo.tjsoa.fileExpress.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cnblogs.zxub.upload.HttpFileUpload;
import com.cnblogs.zxub.upload.HttpFileUpload.InvalidFileUploadException;
import com.tjsinfo.tjsoa.addresslist.bo.IAddressListAndFilePendingBo;
import com.tjsinfo.tjsoa.addresslist.vo.AddressListAndFilePending;
import com.tjsinfo.tjsoa.fileExpress.bo.IFileExpressFileBo;
import com.tjsinfo.tjsoa.fileExpress.bo.IFileExpressGroupBo;
import com.tjsinfo.tjsoa.fileExpress.bo.IFileExpressUserSizeBo;
import com.tjsinfo.tjsoa.fileExpress.vo.FileExpressFile;
import com.tjsinfo.tjsoa.fileExpress.vo.FileExpressGroup;
import com.tjsinfo.tjsoa.fileExpress.vo.TjsUserEmail;
import com.tjsinfo.tjsoa.message.bo.ITjsMessageBo;
import com.tjsinfo.tjsoa.message.vo.TjsMessage;
import com.tjsinfo.tjsoa.system.bo.ISystemUserBo;
import com.tjsinfo.tjsoa.system.vo.TSystemUser;
import com.tjsinfo.tjsoa.system.vo.User;

public class UpLoadAction_old extends Action {
	private IFileExpressUserSizeBo userEmailBo;
	private IFileExpressGroupBo expressGroupBo;
	private ISystemUserBo tjsUserBo;
	private IFileExpressFileBo fileExpressFileBo;
	private IAddressListAndFilePendingBo addressListAndFilePendingBo;
	public ITjsMessageBo tjsMessageBo;
	/*private ITjsMessageBo messageBo;
	public void setMessageBo(ITjsMessageBo messageBo) {
		this.messageBo = messageBo;
	}*/

	public ITjsMessageBo getTjsMessageBo() {
		return tjsMessageBo;
	}

	public void setTjsMessageBo(ITjsMessageBo tjsMessageBo) {
		this.tjsMessageBo = tjsMessageBo;
	}

	public void setAddressListAndFilePendingBo(
			IAddressListAndFilePendingBo addressListAndFilePendingBo) {
		this.addressListAndFilePendingBo = addressListAndFilePendingBo;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String returnUrl = "ok";
		String returnString = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();

		factory.setSizeThreshold(1024 * 1024);
		
		ResourceBundle bundle = ResourceBundle.getBundle("com.tjsinfo.tjsoa.fileExpress.properties.FileExpress");
		String linshiFile = bundle.getString("linshiFile");
		String path = bundle.getString("fileupload");
		factory.setRepository(new File(linshiFile));

		HttpFileUpload fu = new HttpFileUpload(factory);

		fu.setSizeMax(1024 * 1024 * 1024);
		String updateStr = "";
		ArrayList listFileName = new ArrayList();
		ArrayList listfileUser = new ArrayList();
		Map map = new HashMap();
		try {
			List fileItemList = fu.parseRequest(request);
			Iterator fileItemListIte = fileItemList.iterator();
			int filesize = 0;
			while (fileItemListIte.hasNext()) {
				FileItem file = (FileItem) fileItemListIte.next();
				if (!file.isFormField() && !"".equals(file.getName())) {
					filesize += file.getSize();
					listFileName.add(file.getName());
				}
			}
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			TjsUserEmail userEmail = userEmailBo
					.fingByUserId(user.getUser_id());
			
			if (filesize > userEmail.getMaxExpress()) {
				returnString = "您一次传送文件的最大容量为" + userEmail.getMaxExpress()
						/ 1024 / 1024 + "M,本次传输文件过大，如果想提升您的传输容量，请与管理员进行联系！";
				returnUrl = "error";
			}else {
				String jujue = "";
				String jibie = "";
				String beizhu = "";

				FileExpressFile[] expressFile = new FileExpressFile[5];
				TjsUserEmail[] fasongUser = new TjsUserEmail[11];
				String[] expressFileName = new String[5];
				String first = "";
				if (fileItemList != null) {
					FileItem file = (FileItem) fileItemList.get(fileItemList
							.size() - 1);
					if (file.isFormField() || "".equals(file.getName())) {
						String userid = new String(request.getParameter(
								"userid").getBytes("ISO-8859-1"), "UTF-8");
						jibie = new String(request.getParameter("jibie")
								.getBytes("ISO-8859-1"), "UTF-8");
						if (request.getParameter("beizhu") != null
								&& !"".equals(request.getParameter("beizhu"))) {
							beizhu = request.getParameter("beizhu");
							if (beizhu != null && !"".equals(beizhu)) {
								beizhu = beizhu.replace("\r\n","<br/>");
								beizhu = beizhu.replace("\"", "“");
							}
						}
						Integer[] inte = new Integer[userid.split(",").length];
						for (int j = 0; j < inte.length; j++) {
							if (userid.split(",")[j] != null) {
								inte[j] = Integer.valueOf(userid.split(",")[j]);
							}
						}
						List list = userEmailBo.upLoadFingByUserIds(inte);
						
						int j = 0;
						int k = 0;
						
						for (Iterator iterator = list.iterator(); iterator
								.hasNext();) {
							TjsUserEmail email = (TjsUserEmail) iterator.next();
							File file2=new File(path+email.getTjsUser().getUuid()+"\\download\\"); 
							String test[]; 
							test=file2.list();
							if(test!=null){
								if (test.length>0) {
									for (int i = 0; i < test.length; i++) {
										String strdos = "cmd /c del \""+path+email.getTjsUser().getUuid()+"\\download\\"+test[i]+"\"";
										Process process;
										try {
											process = Runtime
													.getRuntime().exec(strdos);
											process.waitFor();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
							}
							
							File ff = new File(path+email.getTjsUser().getUuid()+"\\");
							long l = 0;
							try {
								l = this.getFileSize(ff);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							if (filesize > email.getMaxReception() - l) {
								jujue += email.getTjsUser().getUserName() + ",";
								map.put(email.getTjsUser().getUserName(), "失败");
								listfileUser.add(email.getTjsUser().getUserName());
							} else {
								map.put(email.getTjsUser().getUserName(), "成功");
								listfileUser.add(email.getTjsUser().getUserName());
								fasongUser[j] = email;
								String filename = "";
								if (j == 0) {
									fileItemListIte = fileItemList.iterator();
									while (fileItemListIte.hasNext()) {
										FileItem file1 = (FileItem) fileItemListIte.next();
										if (!file1.isFormField()
												&& !"".equals(file1.getName())) {
											String name = file1.getName();
											if(name.indexOf("\\")!=-1){
												int a = name.lastIndexOf("\\");
												name = name.substring(a+1, name
														.length());
											}
											expressFileName[k] = name;
											Date date = new Date();
											TSystemUser faUser = tjsUserBo
													.findByIdSystemUser(user
															.getUser_id());
											FileExpressFile expressFile1 = new FileExpressFile();
											expressFile1
													.setFileName(name);
											expressFile1.setFilePath(file1
													.getName());
											expressFile1
													.setFileSize(Integer
															.valueOf(String
																	.valueOf(file1
																			.getSize())));
											expressFile1
													.setExpressLevel(Integer
															.valueOf(jibie));
											expressFile1.setRemark(beizhu);
											expressFile1.setDatetime(date);
											expressFile1.setState(Integer
													.valueOf(0));
											expressFile1.setTjsUser(faUser);

											first = email.getTjsUser().getUserId()
													.toString();
											FileExpressGroup expressGroup = expressGroupBo
													.findByMainGroup(email.getTjsUser().getUserId(),
															"我的接收文件夹");
											expressFile1
													.setFileExpressGroup(expressGroup);
											String id = UUID.randomUUID().toString().replace("-", "");
											expressFile1.setId(id);
											fileExpressFileBo
													.save(expressFile1);
											filename = id+ "@&_&@"+name+"";
											while (filename.indexOf("  ")!=-1) {
												filename = filename.replace("  ", " ");
											}
											expressFile1
													.setFileName(filename);
											fileExpressFileBo.updatejdbcName(
													id, filename);
											expressFile[k] = expressFile1;
											k++;
											file1.write(new File(path+email.getTjsUser().getUuid()+"\\"+filename));
										}
									}
								}else{
									for (int m = 0; m < expressFile.length; m++) {
										if (expressFile[m] != null) {
											FileExpressGroup expressGroup = new FileExpressGroup();
											expressGroup = expressGroupBo.findByMainGroup(
													email.getTjsUser().getUserId(),
													"我的接收文件夹");
											String id = UUID.randomUUID().toString().replace("-", "");
											fileExpressFileBo.insert(id,expressGroup.getId(), user.getUser_id(), expressFile[m].getFileName(), sdf.format(expressFile[m].getDatetime()), String.valueOf(expressFile[m].getExpressLevel()), String.valueOf(expressFile[m].getFileSize()), expressFile[m].getFilePath(), expressFile[m].getRemark());
											
											String strdos = "cmd /c copy \""+path+fasongUser[0].getTjsUser().getUuid()+"\\"+expressFile[m].getFileName()+ "\" \""+path+email.getTjsUser().getUuid()+"\\\"";
											Process process = Runtime
													.getRuntime().exec(strdos);
											process.waitFor();
										}
									}
								}
								j++;
							}
						}
					}
					for (int i = 0; i < expressFile.length; i++) {
						if (expressFile[i] != null) {
							updateStr += "'"+expressFile[i].getFileName()+"',";
						}
					}
				}
				if (!"".equals(jujue)) {
					returnString = "接收文件夹已满不能接收此次发送！";
					if(fasongUser[0] != null){
						fileExpressFileBo.updateState(updateStr.substring(0, updateStr.length()-1),String.valueOf(2));
						
						for (int i = 0; i < fasongUser.length-1; i++) {
							if(fasongUser[i] != null){
								TjsUserEmail email = fasongUser[i];
								AddressListAndFilePending message = new AddressListAndFilePending();
								message.setId(UUID.randomUUID().toString().replace("-", ""));
								message.setSendUserId(user.getUser_id());
								message.setSendUserName(user.getUsername());
								message.setCreateTime(new Date());
								message.setTjsUserId(email.getTjsUser().getUserId());
								
								message.setTitle("发送新文件");
								message.setType("文件速递");
								String path1 = request.getContextPath();
								String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/fileExpress/frame.jsp";
								message.setUrl(basePath);
								
								addressListAndFilePendingBo.save(message);
								
								TjsMessage message1 = new TjsMessage();
								message1.setRecuserid(email.getTjsUser().getUserId());
								message1.setValue(user.getUsername()+"向您发送文件，请登录TJSOA进行处理。");
								tjsMessageBo.sendNewMessage(message1);
							}
						}
					}
					returnUrl = "error";
				}else {
					for (int i = 0; i < fasongUser.length-1; i++) {
						if(fasongUser[i] != null){
							TjsUserEmail email = fasongUser[i];
							AddressListAndFilePending message = new AddressListAndFilePending();
							message.setId(UUID.randomUUID().toString().replace("-", ""));
							message.setSendUserId(user.getUser_id());
							message.setSendUserName(user.getUsername());
							message.setCreateTime(new Date());
							message.setTjsUserId(email.getTjsUser().getUserId());
							
							message.setTitle("发送新文件");
							message.setType("文件速递");
							String path1 = request.getContextPath();
							String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/fileExpress/frame.jsp";
							message.setUrl(basePath);
							
							addressListAndFilePendingBo.save(message);
							
							TjsMessage message1 = new TjsMessage();
							message1.setRecuserid(email.getTjsUser().getUserId());
							message1.setValue(user.getUsername()+"向您发送文件，请登录TJSOA进行处理。");
							tjsMessageBo.sendNewMessage(message1);
						}
					}
				}
			}
		}catch (InvalidFileUploadException e) {
			returnString = "本次传输文件过大，如果想提升您的传输容量，请与管理员进行联系！";
			if (e instanceof HttpFileUpload.InvalidFileUploadException) {
				Iterator unAllowFileS = ((HttpFileUpload.InvalidFileUploadException) e)
						.getInvalidFileList().iterator();
				while (unAllowFileS.hasNext()) {
					returnString += "以下文件不被允许" + (String) unAllowFileS.next();
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			returnUrl = "error";
			returnString = "请检查发送文件是否过大及发送人数是否过多！";
			if (e instanceof HttpFileUpload.InvalidFileUploadException) {
				Iterator unAllowFileS = ((HttpFileUpload.InvalidFileUploadException) e)
						.getInvalidFileList().iterator();
				while (unAllowFileS.hasNext()) {
					returnString += "以下文件不被允许" + (String) unAllowFileS.next();
				}
			}
		} finally {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			fu.dispose();
		}
		if (!returnUrl.equals("error") && !"".equals(updateStr)) {
			fileExpressFileBo.updateState(updateStr.substring(0, updateStr.length()-1),String.valueOf(2));
		}
		request.setAttribute("returnString", returnString);
		request.setAttribute("listFileName", listFileName);
		request.setAttribute("listfileUser", listfileUser);
		request.setAttribute("map", map);
		return mapping.findForward("ok");
	}

	public IFileExpressGroupBo getExpressGroupBo() {
		return expressGroupBo;
	}

	public void setExpressGroupBo(IFileExpressGroupBo expressGroupBo) {
		this.expressGroupBo = expressGroupBo;
	}

	public long getFileSize(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	public void setUserEmailBo(IFileExpressUserSizeBo userEmailBo) {
		this.userEmailBo = userEmailBo;
	}

	public void setTjsUserBo(ISystemUserBo tjsUserBo) {
		this.tjsUserBo = tjsUserBo;
	}

	public void setFileExpressFileBo(IFileExpressFileBo fileExpressFileBo) {
		this.fileExpressFileBo = fileExpressFileBo;
	}
}
